package com.course.redis.controller;

import com.course.common.model.vo.SignInUserInfo;
import com.course.common.response.BaseResponse;
import com.course.common.response.StatusCode;
import com.course.common.util.AssertUtil;
import com.course.redis.service.BatchDataService;
import com.course.redis.service.UserPointsService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @PROJECT_NAME: course
 * @DESCRIPTION: 用户积分controller层
 * @Author: 涂玄武
 * @DATE: 2021/7/9 14:24
 */
@RestController
@RequestMapping("points")
public class UserPointsController extends BaseController{

    public static final String BUSINESS_NAME = "用户积分";

    @Resource
    private UserPointsService userPointsService;

    @Resource
    private BatchDataService batchDataService;

    /**
     * 预批量生成百万级别数据
     * @param userTotal
     * @param pointsCount
     * @return
     */
    @PostMapping(value = "batch/data/insert")
    public BaseResponse batchInsertData(@RequestParam Integer userTotal,
                                        @RequestParam Integer pointsCount) throws Exception {
        //参数校验
        AssertUtil.isTrue(userTotal == null || userTotal < 1, "用户总数不能为空!");
        AssertUtil.isTrue(pointsCount == null || pointsCount < 1, "积分记录总数不能为空!");
        //userTotal为批量插入数据的次数，每次数据量为 pointsCount
        batchDataService.batchInitItem(userTotal,pointsCount);
        return new BaseResponse().success("预批量生成百万级别数据成功!");
    }

    /**
     * 用户添加积分
     *
     * @param userId
     * @param points
     * @param types
     * @return
     */
    @PostMapping("add")
    public BaseResponse addPoints(Integer userId, Integer points, Integer types) {
        //参数校验
        AssertUtil.isTrue(userId == null || userId < 1, "用户ID不能为空!");
        AssertUtil.isTrue(points == null || points < 1, "积分不能为空!");
        AssertUtil.isTrue(types == null, "请选择对应的积分类型!");
        userPointsService.addPoints(userId, points, types);
        return new BaseResponse().success("用户添加积分成功");
    }

    /**
     * 查询前 20 积分排行榜，同时显示用户排名 -- MySQL
     * @param access_token
     * @return
     */
    @GetMapping
    public BaseResponse findUserPointsRank(String access_token){
        SignInUserInfo userInfo = loadSignInDinerInfo(access_token);
        return new BaseResponse().success(userPointsService.findUserPointRank(userInfo.getId()));
    }

    /**
     * 查询前 20 积分排行榜，同时显示用户排名 -- Redis
     * @param access_token
     * @return
     */
    @GetMapping("redis")
    public BaseResponse findUserPointsRankFromRedis(String access_token){
        SignInUserInfo userInfo = loadSignInDinerInfo(access_token);
        return new BaseResponse().success(userPointsService.findUserPointRankFromRedis(userInfo));
    }

}
